<template>
    <div class="app-container">
        <!-- 搜索区 -->
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
            <el-form-item label="产品名称" prop="productName">
                <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable size="small"
                    style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="检验日期" prop="checkDate">
                <el-date-picker v-model="queryParams.checkDate" type="date" placeholder="选择日期"
                    value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="质检单号" prop="qualityNumber">
                <el-input v-model="queryParams.qualityNumber" placeholder="请输入质检单号" clearable size="small"
                    style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 200px">
                    <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="产品型号" prop="productModel">
                <el-input v-model="queryParams.productModel" placeholder="请输入产品型号" clearable size="small"
                    style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['set:model:add']">新增</el-button>
            </el-col>

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="llList">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="来料单号" prop="incomingCode" width="120" align="center" />
            <el-table-column label="订单号" prop="orderCode" :show-overflow-tooltip="true" width="150" align="center" />
            <el-table-column label="质检单号" prop="qualityNumber" :show-overflow-tooltip="true" width="150"
                align="center" />
            <el-table-column label="产品名称" prop="productName" :show-overflow-tooltip="true" width="150" align="center" />
            <el-table-column label="零件号" prop="partMark" :show-overflow-tooltip="true" width="150" align="center" />

            <el-table-column label="检验报告" prop="surveyReport" :show-overflow-tooltip="true" width="150"
                align="center" />
            <el-table-column label="库房/检验室" prop="warehouse" :show-overflow-tooltip="true" width="100" align="center" />
            <el-table-column label="产品型号" prop="productModel" :show-overflow-tooltip="true" width="100"
                align="center" />
            <el-table-column label="检验日期" prop="checkDate" :show-overflow-tooltip="true" width="100" align="center" />
            <el-table-column label="结论" prop="conclusion" :show-overflow-tooltip="true" width="100" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.conclusion === '0 '? "不合格": "合格"}}</span>
                </template>
            </el-table-column>
            <el-table-column label="批量数" prop="batchNumber" :show-overflow-tooltip="true" width="100" align="center" />

            <el-table-column label="检验数量" prop="checkoutNumber" :show-overflow-tooltip="true" width="100"
                align="center" />
            <el-table-column label="合格数" prop="hgs" :show-overflow-tooltip="true" width="100" align="center" />
            <el-table-column label="不合格数" prop="acceptanceNumber" :show-overflow-tooltip="true" width="100"
                align="center" />
            <el-table-column label="入库类型" prop="storageType" :show-overflow-tooltip="true" width="100" align="center" />

            <el-table-column label="状态" prop="status" :show-overflow-tooltip="true" width="100" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.status == 0? "待检验": scope.row.status == 1 ? "检验中" : "已完成"}}</span>
                </template>
            </el-table-column>
            <el-table-column label="检验类别" prop="belowStandard" :show-overflow-tooltip="true" width="100" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.belowStandard === '0'? "成品检验单": scope.row.belowStandard == '1' ? "过程检验单" :
                        "来料检验单"}}</span>
                </template>
            </el-table-column>
            <!-- 差一个合格数、单据类型 -->
            <el-table-column label="操作" align="center" width="550" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">数据录入</el-button>
                    <el-button size="mini" type="primary" @click="handleRkd(scope.row)" :disabled="scope.row.judge==='1'"
                        v-if="scope.row.status==='2'">生成入库单</el-button>
                    <el-button size="mini" type="success" icon="el-icon-upload2" :disabled="scope.row.status==='2'"
                        @click="handleImport(scope.row)">上传</el-button>
                    <el-button size="mini" type="success" icon="el-icon-link"
                        @click="detail(scope.row)">附件详情</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" v-if="scope.row.status==='0'"
                        :disabled="scope.row.status==='2'" @click="handleDelete(scope.row)">删除</el-button>
                    <el-button size="mini" type="primary" :disabled="scope.row.status==='2'"
                        @click="completed(scope.row)">完成</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或 修改 对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="110px">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="来料单号" prop="incomingCode">
                            <el-input v-model="form.incomingCode" placeholder="请输入来料单号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单号" prop="orderCode">
                            <el-input v-model="form.orderCode" placeholder="请输入订单号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="质检单号" prop="qualityNumber">
                            <el-input v-model="form.qualityNumber" placeholder="请输入质检单号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="产品名称" prop="productName">
                            <el-input v-model="form.productName" placeholder="请输入产品名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="零件号" prop="partMark">
                            <el-input v-model="form.partMark" placeholder="请输入零件号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="检验报告" prop="surveyReport">
                            <el-input v-model="form.surveyReport" placeholder="请输入检验报告" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="库房/检验室" prop="warehouse">
                            <el-input v-model="form.warehouse" placeholder="请输入库房/检验室" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="产品型号" prop="productModel">
                            <el-input v-model="form.productModel" placeholder="请输入产品型号" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="结论" prop="conclusion">
                            <el-select v-model="form.conclusion" placeholder="请选择结论" clearable size="small"
                                style="width: 200px">
                                <el-option v-for="dict in conclusionOptions" :key="dict.dictValue"
                                    :label="dict.dictLabel" :value="dict.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="批数量" prop="batchNumber">
                            <el-input-number v-model="form.batchNumber" placeholder="请输入批数量" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="检验数量" prop="checkoutNumber">
                            <el-input-number v-model="form.checkoutNumber" placeholder="请输入检验数量" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="合格数" prop="acceptanceNumber">
                            <el-input-number v-model="form.acceptanceNumber" placeholder="请输入合格数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="不合格数" prop="disqualificationNumber">
                            <el-input-number v-model="form.disqualificationNumber" placeholder="请输入不合格数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库类型" prop="storageType">
                            <el-input v-model="form.storageType" placeholder="请输入入库类型" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="form.status" placeholder="请选择状态" clearable size="small"
                                style="width: 200px">
                                <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                                    :value="dict.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="检验类别" prop="belowStandard">
                            <el-select v-model="form.belowStandard" placeholder="请选择检验类别" clearable size="small">
                                <el-option v-for="dict in belowStandardOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="检验日期" prop="checkDate">
                            <el-date-picker v-model="form.checkDate" type="date" placeholder="选择日期"
                                value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 上传-->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload v-show="upload.uploadShow" ref="upload" :limit="5" accept=".png,.jpg,.xls,.xlsx,.doc"
                :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading"
                :http-request="httpRequest" multiple :on-progress="handleFileUploadProgress" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“jpg”“png”“.doc”“xls”或“xlsx”格式文件！</div>
            </el-upload>
            <!-- 附件 -->

            <el-upload v-show="upload.downloadShow" :on-preview="handlePreview" multiple :limit="5"
                :on-exceed="handleExceed" :on-remove="delFile" :file-list="upload.fileList" show-file-list
                :action="upload.url">
                <div v-for="item in upload.fileList">
                    <p>{{item.filename}}</p>
                </div>
            </el-upload>
            <div v-show="upload.downloadShow" v-if="upload.fileList.length===0" style="margin-left: 100px;">暂无文件，请先上传
            </div>
            <div v-show="upload.uploadShow" slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm" v-loading="upload.submitLoading">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="upload.previewOpen" width="400px" height="500px" title="图片预览">
            <img alt="logo" style="width: 100%;height: 100%;" :src="upload.previewImage" />
        </el-dialog>
    </div>
</template>

<script>

    import { getLlList, addLl, uploadLl, delLl, downloadLl, completedLl, rkdLld } from "@/api/mass/lailiao";
    import { getcpList, addCP, delCp, downloadCp, delFile, getFile, preImages, downloadFile, completedCp } from "@/api/mass/end";
    import Axios from "axios";
    import config from "../../../../vue.config";

    import { getToken } from "@/utils/auth";
    export default {
        name: "Lailiao",
        data() {
            return {
                //检验日期
                valueDate: '',
                // 状态字典
                statusOptions: [],
                //检验记录
                inspectionRecordOptions: [],
                // 上传
                upload: {
                    submitLoading: false,
                    fileList: [],
                    uploadShow: false,
                    downloadShow: false,
                    previewOpen: false,
                    previewImage: '',
                    uploadRes: {},
                    uploadFiles: [],
                    fileNameList: [],
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 设置上传的请求头部
                    headers: { Authorization: "Bearer " + getToken() },
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + "/system/file/uploads",
                },
                // 遮罩层
                loading: true,
                // 选中数组
                incomingCodes: [],
                belowStandardOptions: [],
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                conclusionOptions: [],
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 表格数据
                llList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 是否显示弹出层（数据权限）
                openDataScope: false,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    modelDesLocal: undefined,
                    incomingCode: undefined,
                },
                // 表单参数
                form: {},
                defaultProps: {
                    children: "children",
                    label: "label",
                },
                // 表单校验
                rules: {
                    incomingCode: [
                        { required: true, message: "来料单号不能为空", trigger: "blur" },
                    ],
                    productName: [
                        { required: true, message: "产品名称不能为空", trigger: "blur" },
                    ],
                    partMark: [
                        { required: true, message: "零件号不能为空", trigger: "blur" },
                    ],
                },
            };
        },
        created() {
            this.getList();
            this.getDicts("cp_jyd_status").then((response) => {
                this.statusOptions = response.data;
            });
            this.getDicts("conclusion").then((response) => {
                this.conclusionOptions = response.data;
            });
            this.belowStandardOptions = [{ value: 2, label: '来料检验单' }]

        },
        methods: {
            //生成入库单
            handleRkd(row) {
              
                this.$confirm(
                    '请确认产品名称为"' + row.productName + '"立即生成入库单？',
                    "警告",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                ).then(() => {
                    rkdLld(row).then(res => {
                        this.msgSuccess("已生成入库单");
                        // this.$router.push({ pathname: '/cangku/rukuGen/ruku', query: {} })
                        this.$router.push('/cangku/rukuGen/ruku')
                    })
                })


            },
            //完成
            completed(row) {
                const params = { id: row.id, status: row.status }
                this.$confirm(
                    '请确认产品名称为"' + row.productName + '"是否已经上传完附件，完成后不能上传以及删除！',
                    "警告",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(() => {
                        return completedLl(params);
                    })
                    .then(() => {
                        this.getList();
                        this.msgSuccess(`已完成`);
                    })
                    .catch(function () { });
            },
            //删除
            delFile(file) {
                console.log();
                delFile(file.id).then(res => {
                    this.$message({ message: res.msg, type: 'success' });
                })
            },
            //文件详情
            getFile() {
                getFile({ tableId: this.rowId, tableName: 'quality_finished_examine' }).then(res => {
                    this.upload.fileList = res.data.map(item => {
                        if (item.fileName) {
                            return { name: item.fileName, id: item.id, type: item.fileFormat, path: item.filePath }
                        }
                    })
                })
            },
            /** 上传按钮操作 */
            handleImport(row) {
                this.rowId = row.id
                this.upload.title = "上传成品检验单";
                this.upload.uploadShow = true
                this.upload.downloadShow = false
                this.upload.open = true;
            },
            //预览或者下载
            handlePreview(file) {
                console.log('file', file);
                if (file.type === 'png' || file.type === 'jpg') {
                    this.upload.previewImage = config.devServer.proxy[process.env.VUE_APP_BASE_API].target + `system/file/getImgs?name=` + file.name
                    console.log(' this.upload.previewImage ', this.upload.previewImage);
                    this.upload.previewOpen = true
                } else {
                    //下载
                    this.downloadFile(file.name)
                }
            },
            downloadFile(value) {
                window.location.href = config.devServer.proxy[process.env.VUE_APP_BASE_API].target + 'system/file/download?resource=' + value;
            },
            // 文件超出个数的方法
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            // 附件详情按钮
            detail(row) {
                this.upload.title = "成品检验单附件详情";
                this.upload.uploadShow = false
                this.upload.downloadShow = true
                this.upload.open = true;
                this.rowId = row.id
                this.getFile()
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 提交上传文件
            async submitFileForm() {
                this.upload.submitLoading = true
                this.$refs.upload.submit();
                let fd = new FormData()// FormData 对象
                this.upload.uploadFiles.forEach(item => {
                    return fd.append('file', item)
                })
                fd.append('tableName', 'quality_finished_examine')
                fd.append('tableId', this.rowId)
                let url = process.env.VUE_APP_BASE_API + "/system/file/uploads"
                let config = {
                    headers:
                        { Authorization: "Bearer " + getToken() }
                }
                Axios.post(url, fd, config).then(response => {
                    console.log('response', response);
                    if (response.status === 200) {
                        this.upload.submitLoading = false
                        this.upload.open = false;
                        this.upload.isUploading = false;
                        this.$refs.upload.clearFiles();
                        this.$alert(response.data.msg, "导入结果", { dangerouslyUseHTMLString: true });
                        this.getList();
                    }
                })
            },
            // param是自带参数。 this.$refs.upload.submit() 会自动调用 httpRequest方法.在里面取得file
            httpRequest(param) {
                this.upload.uploadFiles.push(param.file)
            },
            /** 查询列表 */
            getList() {
                this.loading = true;
                getLlList(this.addDateRange(this.queryParams, this.dateRange)).then(
                    (response) => {
                        this.llList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    }
                );
            },

            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
                this.getList()
            },

            // 表单重置
            reset() {
                this.form = {

                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                this.handleQuery();
            },

            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加来料检验单";
            },

            handleUpdate(row) {
                this.open = true;
                this.title = "修改来料检验单";
                this.form = row
            },
            /** 提交按钮 */
            submitForm: function () {
                this.$refs["form"].validate((valid) => {
                    if (valid) {
                        if (this.title === '修改来料检验单') {
                            updateLl().then((response) => {
                                if (response.code === 200) {
                                    this.msgSuccess("修改成功");
                                    this.open = false;
                                    this.getList();
                                }
                            });
                        } else {
                            addLl(this.form).then((response) => {
                                if (response.code === 200) {
                                    this.msgSuccess("新增成功");
                                    this.open = false;
                                    this.getList();
                                }
                            });
                        }

                    }
                });
            },

            /** 删除按钮操作 */
            handleDelete(row) {

                this.$confirm(
                    '是否确认删除来料单号为"' + row.incomingCode + '"的数据项?',
                    "警告",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(function () {
                        return delLl(row.id);
                    })
                    .then(() => {
                        this.getList();
                        this.msgSuccess("删除成功");
                    })
                    .catch(function () { });
            },


        },
    };
</script>